<template>
  <div>
    <!--    产品配置-->
    <el-row style="text-align: right;margin: 0" :gutter="24">
      <el-form>
        <el-col :span="6">
          <el-form-item :label="$t('可借状态')" label-width="80px" style="margin-bottom: 0">
            <el-select :placeholder="$t('是否可借')" @change="getTableData" clearable v-model="page.isLoan"
                       style="width: 100%">
              <el-option :value="0" :label="$t('可借')"></el-option>
              <el-option :value="1" :label="$t('不可借')"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item :label="$t('状态')" label-width="80px" style="margin-bottom: 0">
            <el-select @change="getTableData" clearable v-model="page.valid"
                       style="width: 100%">
              <el-option :value="0" :label="$t('禁用')"></el-option>
              <el-option :value="1" :label="$t('启用')"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-button type="primary" @click="addProduct" v-show="panePermiss[130]">{{ $t('新增') }}</el-button>
        </el-col>
      </el-form>
    </el-row>
    <el-row style="margin-top: 10px">
      <Table :page="page" row-key="id" :table-data="tableData" :table-column="tableColumn"
             @handleSizeChange="handleSizeChange"
             @handleCurrentChange="handleCurrentChange">
        <el-table-column :label="$t('APP名称')" prop="appName" align="center" min-width="120"></el-table-column>
        <el-table-column :label="$t('是否可借')" prop="isLoan" align="center">
          <template slot-scope="{row}">
            {{ row.isLoan === 0 ? $t('可借') : $t('不可借') }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('借款金额')" prop="loanAmount" align="center" width="150"></el-table-column>
        <el-table-column :label="$t('评分区间')" prop="loanTerm" align="center" width="120">
          <template slot-scope="{row}">
          <span v-show="row.gradeOne !== undefined">
              {{ row.gradeOne }} <span>~</span> {{ row.gradeTwo }}
          </span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('借款金额2')" prop="loanAmountTwo" align="center" width="150"></el-table-column>
        <el-table-column :label="$t('评分区间2')" prop="loanTerm" align="center" width="120">
          <template slot-scope="{row}">
          <span v-show="row.gradeThree !== undefined">
              {{ row.gradeThree }} <span>~</span> {{ row.gradeFour }}
          </span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('借款周期')" prop="loanTerm" align="center"></el-table-column>

        <el-table-column :label="$t('利息方式')" prop="interestType" align="center">
          <template slot-scope="{row}">
            {{ row.interestType === 1 ? $t('按利率') : row.interestType === 2 ? $t('按金额') : row.interestType }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('周期利率/利息')" prop="loanInterest" width="150" align="center">
          <template slot-scope="{row}">
            {{ row.loanInterest }}<span v-show="row.interestType === 1">%</span>
          </template>
        </el-table-column>

        <el-table-column :label="$t('服务费方式')" prop="poundageType" align="center" width="100">
          <template slot-scope="{row}">
            {{ row.poundageType === 1 ? $t('按利率') : $t('按金额') }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('服务费利率/金额')" min-width="150" prop="loanPoundage" align="center">
          <template slot-scope="{row}">
            {{ row.loanPoundage }}<span v-show="row.poundageType === 1">%</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('逾期日罚息方式')" prop="overdueFineType" align="center" width="120">
          <template slot-scope="{row}">
            {{ row.overdueFineType === 1 ? $t('按利率') : $t('按金额') }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('逾期日罚息利率/金额')" min-width="150" prop="overdueFine" align="center">
          <template slot-scope="{row}">
            {{ row.overdueFine }}<span v-show="row.overdueFineType === 1">%</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('费用扣除方式')" prop="refundWay" align="center" width="100"></el-table-column>
        <el-table-column :label="$t('账单计算方式')" prop="billType" align="center" width="100">
          <template slot-scope="{row}">
            {{ row.billType ? billList.find(item => item.value === row.billType).label : '' }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('创建时间')" prop="createTime" width="150" align="center"></el-table-column>
        <el-table-column :label="$t('更新时间')" prop="updateTime" width="150" align="center"></el-table-column>
        <el-table-column :label="$t('状态')" align="center">
          <template slot-scope="scope">
            <el-switch @change="changeStatus(scope.row)"
                       :disabled="panePermiss[131] ? false : true"
                       :value="scope.row.valid"></el-switch>
          </template>
        </el-table-column>
        <el-table-column :label="$t('操作')" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" @click="editProduct(scope.row)" v-show="panePermiss[132]">{{ $t('编辑') }}</el-button>
          </template>
        </el-table-column>
      </Table>
    </el-row>
    <Dialog :visible.sync="visible.isShow" @cancel="visible.isShow = false" @confirm="visibleConfirm" @close="clearForm"
            :title="visible.title" width="50%" :confirm-loading="confirmLoading">
      <el-form :model="form" ref="form" label-width="130px" :rules="rulesForm">
        <el-row :gutter="24">
          <el-col :span="12" :xs="24">
            <el-form-item :label="$t('APP名称')">
              <el-input v-model="$route.query.productName" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item :label="$t('借款金额')" prop="loanAmount">
              <el-input v-model="form.loanAmount" oninput="value = value.replace(/[^\d.]/g, '')"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item :label="$t('评分区间')" prop="gradeOne">
              <el-row :gutter="24" style="margin: 0">
                <el-col :span="11" :xs="24">
                  <el-input v-model="form.gradeOne"
                            oninput="value = value.replace(/[^\d]/g, '')"></el-input>
                </el-col>
                <el-col :span="2" style="text-align: center;line-height: 32px;"><span>~</span></el-col>
                <el-col :span="11" :xs="24">
                  <el-form-item style="margin-bottom: 0px" label-width="0px" prop="gradeTwo">
                    <el-input v-model="form.gradeTwo"
                              oninput="value = value.replace(/[^\d]/g, '')"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item :label="$t('借款金额2')" prop="loanAmount">
              <el-input v-model="form.loanAmountTwo" oninput="value = value.replace(/[^\d.]/g, '')"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item :label="$t('评分区间2')" prop="gradeThree">
              <el-row :gutter="24" style="margin: 0">
                <el-col :span="11" :xs="24">
                  <el-input v-model="form.gradeThree"
                            oninput="value = value.replace(/[^\d]/g, '')"></el-input>
                </el-col>
                <el-col :span="2" style="text-align: center;line-height: 32px;"><span>~</span></el-col>
                <el-col :span="11" :xs="24">
                  <el-form-item style="margin-bottom: 0px" label-width="0px" prop="gradeTwo">
                    <el-input v-model="form.gradeFour"
                              oninput="value = value.replace(/[^\d]/g, '')"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item :label="$t('利息方式')" prop="interestType">
              <el-select style="width: 100%;" v-model="form.interestType">
                <el-option :value="1" :label="$t('按利率')"></el-option>
                <el-option :value="2" :label="$t('按金额')"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item :label="form.interestType === 1 ? $t('周期利率') : $t('周期利息')" prop="loanInterest">
              <el-input v-model="form.loanInterest" oninput="value = value.replace(/[^\d.]/g, '')">
                <template slot="append" v-if="form.interestType === 1">
                  %
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item :label="$t('服务费方式')" prop="poundageType">
              <el-select style="width: 100%;" v-model="form.poundageType">
                <el-option :value="1" :label="$t('按利率')"></el-option>
                <el-option :value="2" :label="$t('按金额')"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item :label="form.poundageType === 1 ? $t('服务费利率'):$t('服务费金额')" prop="loanPoundage">
              <el-input v-model="form.loanPoundage" oninput="value = value.replace(/[^\d.]/g, '')">
                <template slot="append" v-if="form.poundageType === 1">
                  %
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item :label="$t('逾期日罚息方式')" prop="overdueFineType">
              <el-select style="width: 100%;" v-model="form.overdueFineType">
                <el-option :value="1" :label="$t('按利率')"></el-option>
                <el-option :value="2" :label="$t('按金额')"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item :label="form.overdueFineType === 1 ? $t('逾期日罚息利率'):$t('逾期日罚息金额')" prop="overdueFine">
              <el-input v-model="form.overdueFine" oninput="value = value.replace(/[^\d.]/g, '')">
                <template slot="append" v-if="form.overdueFineType === 1">
                  %
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item :label="$t('借款周期')" prop="loanTerm">
              <el-input v-model="form.loanTerm" oninput="value = value.replace(/[^\d]/g, '')"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24" :xs="24">
            <el-form-item :label="$t('费用扣除方式')">
              <div>
                <el-radio-group v-model="form.refundWay">
                  <el-radio v-for="item in refundWayList" :key="item.value" :label="item.value">{{
                      item.label
                    }}
                  </el-radio>
                </el-radio-group>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24" :xs="24">
            <el-form-item :label="$t('账单计算方式')">
              <div>
                <el-radio-group v-model="form.billType">
                  <el-radio v-for="item in billList" :key="item.value" :label="item.value">{{
                      item.label
                    }}
                  </el-radio>
                </el-radio-group>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24" :xs="24">
            <el-form-item :label="$t('是否可借')" prop="isLoan">
              <el-radio-group v-model="form.isLoan">
                <el-radio :label="0">
                  {{ $t('可借') }}
                </el-radio>
                <el-radio :label="1">
                  {{ $t('不可借') }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </Dialog>
  </div>
</template>

<script>
import {deepClone} from "@/utils/tools";
import {loanProductList, updateLoanProductStatus, addLoanProduct, updateLoanProduct} from '@/api/product'

export default {
  props: ['panePermiss'],
  data() {
    const validatorLoanAmount = (rules, value, callBack) => {
      if (value < 1) {
        callBack(new Error(this.$t('不能小于一天')));
      }
      callBack();
    }
    const validatorNumSize = (rules, value, callBack) => {
      const num = parseFloat(value)
      if (num < 0) {
        callBack(new Error(this.$t('必须输入大于等于0的数值')));
      }
      callBack();
    }
    return {
      tableData: [],
      tableColumn: [],
      form: {
        refundWay: 1,
        termType: 1,
        valid: 1,
        isLoan: 0,
        billType: 1
      },
      rulesForm: {
        loanAmount: [
          {required: true, message: this.$t('不能为空')},
        ],
        loanAmountTwo: [
          {required: false, message: this.$t('不能为空')},
        ],
        loanTerm: [
          {required: true, message: this.$t('不能为空')},
          {required: true, validator: validatorLoanAmount}
        ],
        loanInterest: [
          {required: true, message: this.$t('不能为空')},
          {required: true, validator: validatorNumSize}
        ],
        loanPoundage: [
          {required: true, message: this.$t('不能为空')},
          {required: true, validator: validatorNumSize}
        ],
        overdueFine: [
          {required: true, message: this.$t('不能为空')},
          {required: true, validator: validatorNumSize}
        ],
        interestType: [
          {required: true, message: this.$t('不能为空')},
        ],
        poundageType: [
          {required: true, message: this.$t('不能为空')},
        ],
        overdueFineType: [
          {required: true, message: this.$t('不能为空')},
        ],
        gradeOne: [
          {validator: validatorNumSize, trigger: 'blur'},
          {
            validator: (rules, value, callBack) => {
              const {gradeOne, gradeTwo} = this.form
              if ((typeof (gradeOne) === "undefined" || gradeOne === null || gradeOne === '') && gradeTwo) {
                callBack(new Error(this.$t('不能为空')))
              }
              callBack()
            }, trigger: 'blur'
          }
        ],
        gradeTwo: [
          {validator: validatorNumSize, trigger: 'blur'},
          {
            validator: (rules, value, callBack) => {
              const {gradeOne, gradeTwo} = this.form
              if (gradeOne && (typeof (gradeTwo) === "undefined" || gradeTwo === null || gradeTwo === '')) {
                callBack(new Error(this.$t('不能为空')))
              }
              if (parseInt(gradeOne) > parseInt(gradeTwo)) {
                callBack(new Error(this.$t('区间值设置错误')))
              }
              callBack()
            }, trigger: 'blur'
          }
        ],
        gradeThree: [
          {validator: validatorNumSize, trigger: 'blur'},
          {
            validator: (rules, value, callBack) => {
              const {gradeThree, gradeFour} = this.form
              if ((typeof (gradeThree) === "undefined" || gradeThree === null || gradeThree === '') && gradeFour) {
                callBack(new Error(this.$t('不能为空')))
              }
              callBack()
            }, trigger: 'blur'
          }
        ],
        gradeFour: [
          {validator: validatorNumSize, trigger: 'blur'},
          {
            validator: (rules, value, callBack) => {
              const {gradeThree, gradeFour} = this.form
              if (gradeThree && (typeof (gradeFour) === "undefined" || gradeFour === null || gradeFour === '')) {
                callBack(new Error(this.$t('不能为空')))
              }
              if (parseInt(gradeThree) > parseInt(gradeFour)) {
                callBack(new Error(this.$t('区间值设置错误')))
              }
              callBack()
            }, trigger: 'blur'
          }
        ]
      },
      visible: {
        isShow: false,
        type: '',
        title: '',
      },
      refundWayList: [
        {label: this.$t('先扣除手续费'), value: 1},
        {label: this.$t('先扣除手续费和利息'), value: 2},
        {label: this.$t('到期计算'), value: 3},
      ],
      billList: [
        {label: this.$t('包头包尾'), value: 1},
        {label: this.$t('只包一头'), value: 2},
        {label: this.$t('不包头不包尾'), value: 3},
      ],
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        isLoan: 0
      },
      confirmLoading: false,
    }
  },
  mounted() {
    this.getTableData()
  },
  methods: {
    async getTableData() {
      const {productId} = this.$route.query
      const res = await loanProductList({...this.page, productId})
      if (res.code === 1) {
        const {list, total} = res.data
        this.tableData = list.map(item => {
          item.valid = item.valid === 1
          item.refundWay1 = item.refundWay;
          item.refundWay = this.refundWayList.find(val => val.value === item.refundWay).label
          return item
        })
        this.page = Object.assign({}, this.page, {
          total: total
        })
      }
    },
    clearForm() {
      this.form = {
        refundWay: 1,
        termType: 1,
        valid: 1,
        isLoan: 0,
        billType: 1,
      }
      this.$refs.form.resetFields()
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.getTableData()
    },
    handleCurrentChange(val) {
      this.page.pageNum = val
      this.getTableData()
    },
    async changeStatus(row) {
      const res = await updateLoanProductStatus({
        loanProductId: row.loanProductId,
        valid: row.valid ? 0 : 1,
      })
      if (res.code === 1) {
        this.$message.success(this.$t('修改成功'))
        this.getTableData()
      }
    },
    addProduct() {
      this.visible = {
        title: this.$t('新增产品配置'),
        type: 'add',
        isShow: true
      }
      // 默认回显内容
      if (this.tableData && this.tableData.length) {
        const data = this.tableData[0];
        this.form = {
          ...this.form,
          loanTerm: data.loanTerm,
          loanInterest: data.loanInterest,
          loanPoundage: data.loanPoundage,
          overdueFine: data.overdueFine,
          refundWay: data.refundWay1,
          isLoan: data.isLoan,
          interestType: data.interestType,
          poundageType: data.poundageType,
          overdueFineType: data.overdueFineType,
          billList: data.billList,
          loanAmountTwo: data.loanAmountTwo
          // gradeOne: data.gradeOne,
          // gradeTwo: data.gradeTwo
        }
      }
    },
    editProduct(row) {
      // 深拷贝列表数据
      this.form = Object.assign({}, deepClone(row), {
        refundWay: this.refundWayList.filter(val => val.label === row.refundWay)[0].value
      })
      this.visible = {
        title: this.$t('编辑产品配置'),
        type: 'edit',
        isShow: true
      }
    },
    visibleConfirm() {
      this.$refs.form.validate(async v => {
        if (v) {
          let message = ''
          this.confirmLoading = true
          const params = Object.assign({}, this.form, {
            valid: this.form.valid ? 1 : 0,
            loanAmount: parseFloat(this.form.loanAmount),
            loanAmountTwo: parseFloat(this.form.loanAmountTwo),
            loanInterest: parseFloat(this.form.loanInterest),
            loanPoundage: parseFloat(this.form.loanPoundage),
            overdueFine: parseFloat(this.form.overdueFine),
            gradeOne: parseInt(this.form.gradeOne),
            gradeTwo: parseInt(this.form.gradeTwo)
          })
          let query = this.$route.query
          let api
          if (this.visible.type === 'add') {
            message = this.$t('新增成功')
            api = addLoanProduct({...params, ...query})
          } else {
            // params.termType = this.form.termType === this.$t('按天') ? 1 : this.form.termType === this.$t('按月') ? 2 : 3
            message = this.$t('修改成功')
            api = updateLoanProduct({...params, ...query})
          }
          const res = await api
          if (res.code === 1) {
            this.$message.success(message)
            this.confirmLoading = false
            this.clearForm()
            this.visible.isShow = false
            this.getTableData()
          } else {
            this.confirmLoading = false
          }
        }
      })
    },

  }
}
</script>

<style scoped>

</style>
